<template>
    <view class="report-container">
        <!-- 固定顶部区域 -->
        <view class="fixed-header">
            <!-- 提示文本 -->
            <view class="tip-header">
                <text class="tip-text">本检测报告基于平台随机抽样盲检，检测结果仅与该送检产品有关。检测报告仅作为平台内部质量控制之用。</text>
            </view>

            <!-- 标签切换栏 -->
            <view class="tab-list">
                <scroll-view scroll-x="true" class="tab-scroll" show-scrollbar="false">
                    <view class="tab-items">
                        <view v-for="(tab, index) in tabList" :key="index"
                            :class="['tab-item', activeTab === index ? 'active' : '']" @click="switchTab(index)">
                            <view class="tab-c">
                                <text class="tab-date">{{ tab.detection_date }}</text>
                                <text class="tab-count">第{{ tab.time }}次</text>
                            </view>

                            <view class="tab-content">
                                <text class="new-tag" v-if="tab.isNew">新</text>
                                <text class="tab-text">{{ tab.title }}</text>
                            </view>
                        </view>
                    </view>
                </scroll-view>
            </view>
        </view>

        <!-- 可滚动的报告图片列表 -->
        <scroll-view class="report-scroll" scroll-y="true" :scroll-top="scrollTop" @scroll="handleScroll">
            <image v-for="(img, index) in currentImages" :key="index" :src="img" mode="widthFix" class="report-image"
                @click="previewImage(img)">
            </image>
        </scroll-view>

        <!-- 固定底部按钮 -->
        <view class="fixed-buttons">
            <view class="action-button" @click="handleShare">
                <image src="../static/img/share.png" class="button-icon"></image>
                <!-- <text>分享</text> -->
            </view>
            <view class="action-button" @click="handleSave">
                <image src="../static/img/down.png" class="button-icon"></image>
                <!-- <text>保存图片</text> -->
            </view>
            <view class="pro-info" @click="toPro()">
                <image :src="product.pic" class="pro-icon"></image>
                <text class="pro-text">查看商品</text>
            </view>
        </view>

        <view class="posterDialog" v-if="showposter" @tap.stop="posterDialogClose">
            <view class="main">
                <!-- <view class="close" @tap="posterDialogClose">
                    <image class="img" src="/static/img/close.png" />
                </view> -->
                <view class="content">
                    <image class="img" :src="posterpic" mode="widthFix" @tap="previewImage" :data-url="posterpic">
                    </image>
                </view>
            </view>
            <button class="pd" @tap="pd" :style="{ background: t('color1') }">下载</button>
        </view>


        <view v-if="sharetypevisible" class="popup__container">
            <view class="popup__overlay" @tap.stop="handleClickMask"></view>
            <view class="popup__modal" style="height:320rpx;min-height:320rpx">
                <view class="popup__content">
                    <view class="sharetypecontent">
                        <button class="f1" @tap="shareyh" open-type="share">
                            <image class="img" src="/static/img/weixin.png" />
                            <text class="t1">分享给好友</text>
                        </button>
                        <view class="f2" @tap="showPoster">
                            <image class="img" src="../static/img/share_poster.png" />
                            <text class="t1">生成分享图片</text>
                        </view>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
var app = getApp();
export default {
    data() {
        return {
            app_name: app.globalData.initdata.name || '',
            static_url: app.globalData.static_url,
            proid: 0,
            activeTab: 0,
            scrollTop: 0,
            tabList: [
                // {
                //     date: '2025.02.12',
                //     count: '8',
                //     isNew: true,
                //     text: '通过内二醛及三聚氰胺检测'
                // },
                // {
                //     date: '2025.02.11',
                //     count: '7',
                //     isNew: true,
                //     text: '通过111项兽残检测'
                // },
                // {
                //     date: '2024.11.12',
                //     count: '6',
                //     isNew: false,
                //     text: '通过远方1项微生物检测'
                // }
            ],
            imagesList: [
                // // 第一组图片
                // [
                //     'https://heda123.oss-cn-guangzhou.aliyuncs.com/upload/3/20250121/e41d7fe8ead48f06290c699d6d6d36e9.jpg',
                //     'https://heda123.oss-cn-guangzhou.aliyuncs.com/upload/3/20250121/e41d7fe8ead48f06290c699d6d6d36e9.jpg'
                // ],
                // // 第二组图片
                // [
                //     'https://heda123.oss-cn-guangzhou.aliyuncs.com/upload/3/20250121/e41d7fe8ead48f06290c699d6d6d36e9.jpg',
                //     'https://heda123.oss-cn-guangzhou.aliyuncs.com/upload/3/20250121/e41d7fe8ead48f06290c699d6d6d36e9.jpg',
                //     'https://heda123.oss-cn-guangzhou.aliyuncs.com/upload/3/20250121/e41d7fe8ead48f06290c699d6d6d36e9.jpg'
                // ],
                // // 第三组图片
                // [
                //     'https://heda123.oss-cn-guangzhou.aliyuncs.com/upload/3/20250121/e41d7fe8ead48f06290c699d6d6d36e9.jpg'
                // ]
            ],
            product: {},
            posterpic: "",
            sharetypevisible: false,
            showposter: false,
            share_title: '',
            share_path: '',
            share_imageUrl: '',
        }
    },
    computed: {
        currentImages() {
            // return this.imagesList[this.activeTab] || []
            return this.tabList[this.activeTab].pics
        }
    },
    onLoad(opt) {
        console.log(opt.proid)
        this.proid = opt.proid;
        this.getdata();
    },
    onShareAppMessage() {
        return {
            title: this.share_title,
            path: this.share_path,
            imageUrl: this.share_imageUrl,
        };
    },

    methods: {
        getdata() {
            let that = this;
            app.showLoading('加载中');
            app.get('ShopProductDetection/productDetectionList', { proid: that.proid }, function (res) {
                if (res.status == 200) {
                    that.tabList = res.data.list;
                    that.product = res.data.product;
                    that.share_title = '[' + that.app_name + '检测报告]' + that.product.name;
                    that.share_path = '/pagesSocial/detection/report?proid=' + that.proid;
                    that.share_imageUrl = that.product.pic;
                    if (res.data.list.length > 0) {
                        // 1. 解析输入日期
                        const targetDate = new Date(res.data.list[0].detection_date);
                        if (isNaN(targetDate.getTime())) {
                            console.error('无效的日期格式，请使用 "YYYY-MM-DD" 格式');
                        }
                        // 2. 获取当前时间（去掉时分秒）
                        const now = new Date();
                        const currentDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
                        // 3. 计算相差天数
                        const timeDiff = targetDate.getTime() - currentDate.getTime();
                        const dayDiff = Math.abs(timeDiff / (1000 * 60 * 60 * 24));
                        // 4. 判断是否在一周左右范围内
                        if (dayDiff <= 7) {
                            that.tabList[0] = {
                                ...that.tabList[0], // 展开原有属性
                                isNew: true         // 添加新属性
                            };
                        }
                    }
                } else {
                    app.error(res.msg)
                }
                app.showLoading(false);
            });
        },
        switchTab(index) {
            this.activeTab = index
            this.scrollTop = 0 // 切换标签时滚动到顶部
        },
        handleScroll(e) {
            this.scrollTop = e.detail.scrollTop
        },
        previewImage(current) {
            uni.previewImage({
                urls: this.currentImages,
                current
            })
        },
        handleShare() {
            this.sharetypevisible = true
        },
        handleSave() {
            var _this = this
            let dimg = []
            _this.tabList[_this.activeTab].pics.forEach(item => {
                dimg.push(item)
            })
            dimg.forEach(i => {
                // var src = this.sharePoster;
                let src = i;
                //#ifdef MP-WEIXIN
                //提前向用户发起授权请求
                uni.authorize({
                    scope: 'scope.writePhotosAlbum',
                    success() {
                        console.log('dp-previewImage:允许储存');
                        _this.downloadImg(src);
                    }
                });
                //#endif

                //#ifdef APP-PLUS
                _this.downloadImg(src);
                //#endif

                //#ifdef H5
                //非同源图片将直接打开
                var abtn = document.createElement('a');
                abtn.href = src;
                abtn.download = '';
                abtn.target = '_blank';
                abtn.click();
                //#endif
            });
        },
        shareyh() {
            let that = this;
            uni.share({
                title: that.share_title,
                path: that.share_path,
                imageUrl: that.share_imageUrl,
            });
        },

        toPro() {
            app.goto('/pages/shop/product?id=' + this.proid)
        },

        //下载并保存文件
        downloadImg(src) {
            //下载图片文件
            uni.showLoading({
                title: '大图提取中'
            });
            uni.downloadFile({
                url: src,
                success: function (res) {
                    console.log('dp-previewImage:下载成功');
                    uni.hideLoading();
                    uni.saveImageToPhotosAlbum({
                        filePath: res.tempFilePath,
                        success: () => {
                            uni.showToast({
                                title: '已保存至相册',
                                duration: 1000
                            });
                        }
                    });
                },
                fail: function () {
                    uni.hideLoading();
                    uni.showToast({
                        title: '图片下载失败',
                        icon: 'none',
                        duration: 1000
                    });
                }
            });
        },

        pd() {
            this.downloadImg(this.posterpic)
        },

        posterDialogClose: function () {
            this.showposter = false;
        },
        handleClickMask: function () {
            this.sharetypevisible = false
        },
        showPoster: function () {
            var that = this;
            that.showposter = true;
            that.sharetypevisible = false;
            app.showLoading('生成海报中');
            app.post('ShopProductDetection/getposter', {
                proid: that.product.id
            }, function (data) {
                app.showLoading(false);
                if (data.status == 0) {
                    app.alert(data.msg);
                } else {
                    that.posterpic = data.poster;
                }
            });
        },
    }
}
</script>

<style lang="scss">
.report-container {
    height: 100vh;
    display: flex;
    flex-direction: column;
    background: #f5f5f5;
    position: relative;

    .fixed-header {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        background: #fff;
        z-index: 100;

        .tip-header {
            padding: 24rpx;
            background: linear-gradient(to right, #f0f9f6, #f5f5f5);

            .tip-text {
                font-size: 28rpx;
                color: #666;
                line-height: 1.6;
            }
        }

        .tab-list {
            padding: 20rpx 0;
            background: #fff;
            // box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
            background: linear-gradient(to right, #f0f9f6, #f5f5f5);

            .tab-scroll {
                width: 100%;
                white-space: nowrap;

                .tab-items {
                    padding: 0 20rpx;
                    display: inline-flex;

                    .tab-item {
                        display: inline-flex;
                        flex-direction: column;
                        padding: 16rpx 24rpx;
                        // background: #f8f8f8;
                        border-radius: 12rpx;
                        margin-right: 20rpx;
                        width: 35vw;

                        &.active {
                            // background: #e6f7f1;
                            border: #00b578 2rpx solid;

                            // .tab-date,
                            // .tab-count,
                            // .tab-text {
                            //     color: #00b578;
                            // }
                        }

                        .tab-c {
                            display: flex;
                            justify-content: center;
                            align-items: center;

                            .tab-date {
                                font-size: 28rpx;
                                color: #00b578;
                                margin-bottom: 8rpx;
                            }

                            .tab-count {
                                font-size: 24rpx;
                                color: #00b578;
                                margin-left: 3rpx;
                                margin-bottom: 8rpx;
                                background-color: #EBFAF6;
                            }
                        }



                        .tab-content {
                            display: flex;
                            align-items: center;

                            .new-tag {
                                background: #ff6b6b;
                                color: #fff;
                                font-size: 20rpx;
                                padding: 2rpx 8rpx;
                                border-radius: 4rpx;
                                margin-right: 8rpx;
                            }

                            .tab-text {
                                font-size: 26rpx;
                                color: #333;
                                text-wrap: wrap;
                            }
                        }
                    }
                }
            }
        }
    }

    .report-scroll {
        flex: 1;
        padding: 20rpx;
        margin-top: 240rpx; // 为固定头部预留空间

        .report-image {
            width: 100%;
            margin-bottom: 20rpx;
            border-radius: 12rpx;
        }
    }

    .fixed-buttons {
        position: fixed;
        right: 40rpx;
        bottom: 60rpx;
        display: flex;
        flex-direction: column;
        gap: 20rpx;
        z-index: 100;

        .action-button {
            width: 80rpx;
            height: 80rpx;
            background: #fff;
            border-radius: 50%;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            margin: 0 auto;

            .button-icon {
                width: 50rpx;
                height: 50rpx;
                // margin-bottom: 4rpx;
            }

            // text {
            //     font-size: 20rpx;
            //     color: #fff;
            // }
        }

        .pro-info {
            display: flex;
            flex-direction: column;
            border-radius: 20rpx;
            overflow: hidden;

            .pro-icon {
                width: 120rpx;
                height: 120rpx;


            }

            .pro-text {
                position: absolute;
                font-size: 24rpx;
                margin: 0 auto;
                color: #fff;
                text-align: center;
                background: linear-gradient(to top,
                        /* 渐变方向（默认从上到下，可不写） */
                        rgba(128, 128, 128, 1),
                        /* 起始颜色（灰色，不透明） */
                        rgba(128, 128, 128, 0)
                        /* 结束颜色（灰色，完全透明） */
                    );
                ;
                opacity: 0.8;
                bottom: 0;
                width: 100%;
                border-radius: 0 0rpx 20rpx 20rpx;
            }

        }
    }

    .popup__container {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        width: 100%;
        height: auto;
        z-index: 100;
        background: #fff;

        .popup__overlay {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            width: 100%;
            height: 100%;
            z-index: 11;
            opacity: 0.3;
            background: #000
        }

        .popup__modal {
            width: 100%;
            position: absolute;
            bottom: 0;
            color: #3d4145;
            overflow-x: hidden;
            overflow-y: hidden;
            opacity: 1;
            padding-bottom: 20rpx;
            background: #fff;
            border-radius: 20rpx 20rpx 0 0;
            z-index: 12;
            min-height: 600rpx;
            max-height: 1000rpx;

            .popup__title {
                text-align: center;
                padding: 30rpx;
                position: relative;
                position: relative
            }

            .popup__title-text {
                font-size: 32rpx
            }

            .popup__close {
                position: absolute;
                top: 34rpx;
                right: 34rpx
            }

            .popup__content {
                width: 100%;
                max-height: 880rpx;
                overflow-y: scroll;
                padding: 20rpx 0;
            }
        }
    }

    .posterDialog {
        z-index: 101;

        .pd {
            background-color: #06B68F;
            z-index: 102;
            width: 70%;
            height: 80rpx;
            line-height: 80rpx;
            color: #fff;
            border-radius: 20rpx;
        }
    }
}
</style>
